using System;
using System.Collections.Generic;
using UnityEngine;

public class Calculator
{
    private static string AnalyzeInteger(string number)
    {
        // 分析数字
        if (!number.Contains('e'))
        {
            return number;
        }

        string[] parts = number.Split('e');
        string basePart = parts[0], exponentPart = parts[1];
        for (int j = 0; j < int.Parse(exponentPart); j++)
        {
            basePart += "0";
        }
        return basePart;
    }

    public static Number AnalyzeFormula(string formula, Number x)
    {
        // 解析公式
        Stack<Number> stack = new Stack<Number>();
        string[] tokens = formula.Split(" ");
        for (int i = 0; i < tokens.Length; i++)
        {
            string token = tokens[i];
            switch (token)
            {
                case "x":
                    stack.Push(x);
                    break;
                case "+":
                    stack.Push(new Number(AnalyzeInteger(tokens[++i]), true, 0, true));
                    break;
                case "-":
                    stack.Push(new Number(AnalyzeInteger(tokens[++i]), false, 0, true));
                    break;
                case "*":
                    if (tokens[i + 1] == "x")
                    {
                        stack.Push(stack.Pop() * x); ++i;
                    }
                    else if (tokens[i + 1] == "(")
                    {
                        stack.Push(stack.Pop() * new Number(AnalyzeInteger(tokens[++i]), true, 0, true));
                    }
                    break;
                case "/":
                    if (tokens[i + 1] == "x")
                    {
                        stack.Push(stack.Pop() / x); ++i;
                    }
                    else if (tokens[i + 1] == "(")
                    {
                        stack.Push(stack.Pop() / new Number(AnalyzeInteger(tokens[++i]), true, 0, true));
                    }
                    break;
                default:
                    stack.Push(new Number(AnalyzeInteger(token), true, 0, true));
                    break;
            }
        }

        Number ans = Number.Zero;
        while (stack.Count > 0)
        {
            ans += stack.Pop();
        }

        return ans;
    }
}